import React, {useEffect, useRef, useState} from 'react';
import {Flex, Image, message, Modal, Radio} from 'antd';
import { Button, Col, DatePicker, Drawer, Form, Input, Row, Select, Space } from 'antd';

import { ExclamationCircleFilled } from '@ant-design/icons';
import {
    DownloadOutlined,
    DeleteOutlined,
    ZoomInOutlined,
    ZoomOutOutlined,
    PlusCircleOutlined,
    PlusOutlined,
    EditOutlined
} from '@ant-design/icons';
import VideoWallpaperTag from '../assets/video-wallpaper.svg';
import TextArea from "antd/es/input/TextArea";
import {hover} from "@testing-library/user-event/dist/hover";
import { postDataAdmin} from "../apis/api";
import {WallpaperListType} from "./AppForAdmin";


export interface WallpaperEntity {
    path: string;
    name: string;
    id: number;
    previewPath: string;
    tag: string;
    description: string;
    score: number;
    officialScore: number;
    interactScore: number;
    status: number;

    likes:number;
    dislikes:number;
    shares:number;
    subscribes:number;

}
interface WallpaperObjectProps {
    wallpaper: WallpaperEntity;
    updateResult: () => void;
}

function isVideo(path: string): boolean {
    const ext = path.split('.').pop();
    return ext === 'mp4';
}
const WallpaperObject: React.FC<WallpaperObjectProps> = ({ wallpaper, updateResult }) => {

    const [isHovered, setIsHovered] = useState(false);
    const [messageApi, contextHolder] = message.useMessage();

    const handleMouseEnter = () => {
        setIsHovered(true);
    };

    const handleMouseLeave = () => {
        setIsHovered(false);
    };
    const onDownload = () => {
        fetch(wallpaper.path)
            .then((response) => response.blob())
            .then((blob) => {
                const url = URL.createObjectURL(new Blob([blob]));
                const link = document.createElement('a');
                link.href = url;
                if (isVideo(wallpaper.path)){
                    link.download = wallpaper.name+'.mp4';
                } else {
                    link.download = wallpaper.name+'.png';
                }
                document.body.appendChild(link);
                link.click();
                URL.revokeObjectURL(url);
                link.remove();
            });
    };

    const onApplyWallpaper = () => {
        // 预期：跳转到另一个页面（带小尾巴），或者发送id到background.js
        console.log("应用壁纸“"+wallpaper.name+"”："+wallpaper.id);
    }
    const onEditWallpaper = () => {
        // 编辑壁纸 弹出编辑面板
        showDrawer();
    }

    const { confirm } = Modal;

    const showConfirm = () => {
        confirm({
            title: '你确定要删除这张壁纸吗？',
            icon: <ExclamationCircleFilled />,
            cancelText: "取消",
            okText: "删除",
            okType: "danger",
            content: '删除后壁纸状态变为已删除，可以找回',
            onOk() {
                onDeleteWallpaper();
            },
            onCancel() {
            },
        });
    };
    const onDeleteWallpaper = async () => {
        // 删除壁纸，确认后执行删除
        try {
            await postDataAdmin('/admin/wallpaper/delete', {id : wallpaper.id});
        } catch (error) {
            console.error(error);
            message.open({
                type: 'error',
                content: '壁纸删除失败',
            });
        } finally {
            updateResult();
            message.open({
                type: 'success',
                content: '壁纸已删除',
            });
        }
    }
    const [open, setOpen] = useState(false);

    const showDrawer = () => {
        setOpen(true);
    };

    const onClose = () => {
        setOpen(false);
    };

    const [form] = Form.useForm();

    const onEditSubmit = async () => {
        try {
            // 进行表单字段的验证
            const values = await form.validateFields();
            // 如果验证通过，调用传入的 onEditSubmit 方法并传递表单数据
            // console.log(values);
            // 调用管理员-更新接口
            await postDataAdmin('/admin/wallpaper/edit',
                {
                    id : wallpaper.id,
                    name : values.name,
                    description : values.description,
                    tag : values.tag,
                    score : values.score,
                    status : values.status,

                    });

        } catch (errorInfo) {
            console.error(errorInfo);
            message.open({
                type: 'error',
                content: '壁纸编辑失败',
            });
        } finally {
            updateResult();
            message.open({
                type: 'success',
                content: '壁纸编辑完成',
            });
        }
    };


    if (isVideo(wallpaper.path)) {
        // 动态壁纸
        return (<div className="wallpaper-preview" style={{margin:"8px"}}>
            <Image
                preview={{
                    destroyOnClose: true,
                    imageRender: () => (
                        <video
                            autoPlay
                            muted
                            width="80%"
                            loop
                            src={wallpaper.path}
                        />
                    ),
                    toolbarRender: (
                        _,
                        {
                        },
                    ) => (
                        <Space size={20} style={{fontSize:"40px"}} className="toolbar-wrapper">
                            <DownloadOutlined onClick={onDownload} />
                            <PlusCircleOutlined onClick={onApplyWallpaper} />
                        </Space>
                    ),
                }}
                src={wallpaper.previewPath.replace("{width}","600").replace("{height}","400")}
                className={"image-preview"}
                style={{borderRadius:"8px",
                    width: '31vw',
                    height: '20vw',
                    maxWidth : '310px',
                    maxHeight : '200px'
                }}
                alt={wallpaper.name}
            />

            <Flex vertical={false}
                  style={{position:"absolute",
                      top:"5px",
                      width:"100%",
                      flexDirection:"row-reverse"}}
                  className={"wallpaperButtonDiv"}
            >
                <button
                    style={{
                        background: "rgba(0, 0, 0, 0.5)",
                        border: "none",
                        borderRadius: "5px",
                        cursor: "pointer"
                    }}
                    className={"wallpaperOpButton"}
                    onClick={onEditWallpaper}
                >

                    <EditOutlined />
                    编辑
                </button>
                {wallpaper.status!==-2 && (<button
                style={{
                    background: "rgba(0, 0, 0, 0.5)",
                    border: "none",
                    borderRadius: "5px",
                    cursor: "pointer"
                }}
                className={"wallpaperOpButton wallpaperOpButtonAlert"}
                onClick={showConfirm}
            >

                <DeleteOutlined />
                删除
            </button>)}

            </Flex>
            <div className={"wallpaperStatusBanner"}
                 style={{
                     background: "rgba(0, 0, 0, 0.5)",
                     color: "#fff",
                     position:"absolute",
                     width:"31vw",
                     maxWidth:"310px",
                     bottom:"0",
                     textAlign: "center",
                     borderRadius:"0 0 6px 6px"
                 }}>
                状态：{
                wallpaper.status === -2 ? <span style={{color:"#f2b3b3"}}>删除</span> :
                    (wallpaper.status === -1 ? <span style={{color:"#e88c0b"}}>不通过</span> :
                        (wallpaper.status === 0 ? <span style={{color:"#e9cb7f"}}>审核中</span>:
                            (wallpaper.status === 1 ? <span style={{color:"#4fe442"}}>通过</span> : "未知状态")))
            }
            </div>
            <div className={"wallpaperNameBanner"}
                 style={{
                     background: "rgba(0, 0, 0, 0.5)",
                     color: "#fff",
                     position:"absolute",
                     width:"31vw",
                     maxWidth:"310px",
                     bottom:"0",
                     textAlign: "center",
                     borderRadius:"0 0 6px 6px"
                 }}>
                名称：{wallpaper.name}, 总分数：{wallpaper.score}
                <br></br>
                标签：{wallpaper.tag}
                <br></br>
                {wallpaper.description}
                <br></br>
                状态：{
                wallpaper.status === -2 ? <span style={{color:"#f2b3b3"}}>删除</span> :
                    (wallpaper.status === -1 ? <span style={{color:"#e88c0b"}}>不通过</span> :
                        (wallpaper.status === 0 ? <span style={{color:"#e9cb7f"}}>审核中</span>:
                            (wallpaper.status === 1 ? <span style={{color:"#4fe442"}}>通过</span> : "未知状态")))
            }
            </div>


            <img
                src={VideoWallpaperTag}
                alt="动态视频"
                style={{
                    position:"absolute",
                    top: "0",
                    left: "-1px",
                    width:"40px",
                    height:"30px",
                    zIndex:"1",
                }}
            />
                <Drawer title="壁纸编辑" onClose={onClose} open={open}
                        extra={
                            <Space>
                                <Button onClick={onClose}>取消</Button>
                                <Button onClick={onEditSubmit} type="primary">
                                    保存
                                </Button>
                            </Space>
                        }>
                    <Form layout="vertical" hideRequiredMark form={form}
                          initialValues={{
                              name: wallpaper.name,
                              tag: wallpaper.tag,
                              description: wallpaper.description,
                              score: wallpaper.score,
                              status: wallpaper.status
                          }}>
                        <Row gutter={16}>
                            <Col span={24}>
                                <Form.Item
                                    name="name"
                                    label="壁纸名称"
                                >
                                    <Input placeholder="壁纸的标题"/>
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row gutter={16}>
                            <Col span={24}>
                                <Form.Item
                                    name="tag"
                                    label="标签"
                                >
                                    <Input placeholder="壁纸的标签，逗号分割" />
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row gutter={16}>
                            <Col span={24}>
                                <Form.Item
                                    name="description"
                                    label="描述"
                                >
                                    <TextArea placeholder="壁纸详细描述" />
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row gutter={16}>
                            <Col span={24}>
                                <Form.Item
                                    name="score"
                                    label="官方分数"
                                >
                                    <Input placeholder="官方的评分，和互动分数求和后排序" />
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row gutter={16}>
                            <Col span={24}>
                                <Form.Item
                                    name="status"
                                    label="状态"
                                >
                                    <Radio.Group>
                                        <Radio value={-2}>已删除</Radio>
                                        <Radio value={-1}>不通过</Radio>
                                        <Radio value={0}>审核中</Radio>
                                        <Radio value={1}>通过</Radio>
                                    </Radio.Group>
                                </Form.Item>
                            </Col>
                        </Row>

                        <div style={{overflowWrap:"anywhere"}}>
                            壁纸路径：
                            <br></br>
                            {wallpaper.path}
                            <br></br>
                            其他信息:
                            <br></br>
                            总分数：{wallpaper.score}
                            <br></br>
                            互动分数：{wallpaper.interactScore}
                            <br></br>
                            喜欢：{wallpaper.likes}，收藏：{wallpaper.subscribes}，分享：{wallpaper.shares}
                            <br></br>
                            <span style={{color:"#FF2222"}}>不喜欢：</span>{wallpaper.dislikes}
                        </div>
                    </Form>
                </Drawer>
            </div>
        );

    } else {
        // 静态壁纸
        return (
            <div className="wallpaper-preview" style={{margin:"8px"}}>
                <Image

                    className={"image-preview"}
                    style={{borderRadius:"8px",
                        width: '31vw',
                        height: '20vw',
                        maxWidth : '310px',
                        maxHeight : '200px'
                    }}
                    alt={wallpaper.name}
                    src={wallpaper.path}
                    preview={{
                        toolbarRender: (
                        ) => (
                            <Space size={20} style={{fontSize:"40px"}} className="toolbar-wrapper">
                                <DownloadOutlined onClick={onDownload} />
                                <PlusCircleOutlined onClick={onApplyWallpaper} />
                            </Space>
                        ),
                    }}
                />
                <Flex vertical={false}
                    style={{position:"absolute",
                    top:"5px",
                    width:"100%",
                    flexDirection:"row-reverse"}}
                      className={"wallpaperButtonDiv"}
                >
                    <button
                        style={{
                            background: "rgba(0, 0, 0, 0.5)",
                            border: "none",
                            borderRadius: "5px",
                            cursor: "pointer"
                        }}
                        className={"wallpaperOpButton"}
                        onClick={onEditWallpaper}
                    >

                        <EditOutlined />
                        编辑
                    </button>

                    {wallpaper.status!==-2 && (<button
                        style={{
                            background: "rgba(0, 0, 0, 0.5)",
                            border: "none",
                            borderRadius: "5px",
                            cursor: "pointer"
                        }}
                        className={"wallpaperOpButton wallpaperOpButtonAlert"}
                        onClick={showConfirm}
                    >

                        <DeleteOutlined />
                        删除
                    </button>)}
                </Flex>
                <div className={"wallpaperStatusBanner"}
                     style={{
                         background: "rgba(0, 0, 0, 0.5)",
                         color: "#fff",
                         position:"absolute",
                         width:"31vw",
                         maxWidth:"310px",
                         bottom:"0",
                         textAlign: "center",
                         borderRadius:"0 0 6px 6px"
                     }}>
                    状态：{
                    wallpaper.status === -2 ? <span style={{color:"#f2b3b3"}}>删除</span> :
                        (wallpaper.status === -1 ? <span style={{color:"#e88c0b"}}>不通过</span> :
                            (wallpaper.status === 0 ? <span style={{color:"#e9cb7f"}}>审核中</span>:
                                (wallpaper.status === 1 ? <span style={{color:"#4fe442"}}>通过</span> : "未知状态")))
                }
                </div>
                <div className={"wallpaperNameBanner"}
                     style={{
                         background: "rgba(0, 0, 0, 0.5)",
                         color: "#fff",
                         position:"absolute",
                         width:"31vw",
                         maxWidth:"310px",
                         bottom:"0",
                         textAlign: "center",
                         borderRadius:"0 0 6px 6px"
                     }}>
                    名称：{wallpaper.name}, 总分数：{wallpaper.score}
                    <br></br>
                    标签：{wallpaper.tag}
                    <br></br>
                    {wallpaper.description}
                    <br></br>
                    状态：{
                    wallpaper.status === -2 ? <span style={{color:"#f2b3b3"}}>删除</span> :
                        (wallpaper.status === -1 ? <span style={{color:"#e88c0b"}}>不通过</span> :
                            (wallpaper.status === 0 ? <span style={{color:"#e9cb7f"}}>审核中</span>:
                                (wallpaper.status === 1 ? <span style={{color:"#4fe442"}}>通过</span> : "未知状态")))
                }
                </div>
                <Drawer title="壁纸编辑" onClose={onClose} open={open}
                        extra={
                            <Space>
                                <Button onClick={onClose}>取消</Button>
                                <Button onClick={onEditSubmit} type="primary">
                                    保存
                                </Button>
                            </Space>
                        }>
                    <Form layout="vertical" hideRequiredMark form={form}
                          initialValues={{
                              name: wallpaper.name,
                              tag: wallpaper.tag,
                              description: wallpaper.description,
                              score: wallpaper.officialScore,
                              status: wallpaper.status
                          }}>
                        <Row gutter={16}>
                            <Col span={24}>
                                <Form.Item
                                    name="name"
                                    label="壁纸名称"
                                >
                                    <Input placeholder="壁纸的标题"/>
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row gutter={16}>
                            <Col span={24}>
                                <Form.Item
                                    name="tag"
                                    label="标签"
                                >
                                    <Input placeholder="壁纸的标签，逗号分割" />
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row gutter={16}>
                            <Col span={24}>
                                <Form.Item
                                    name="description"
                                    label="描述"
                                >
                                    <TextArea placeholder="壁纸详细描述" />
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row gutter={16}>
                            <Col span={24}>
                                <Form.Item
                                    name="score"
                                    label="官方分数"
                                >
                                    <Input placeholder="官方的评分，和互动分数求和后排序" />
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row gutter={16}>
                            <Col span={24}>
                                <Form.Item
                                    name="status"
                                    label="状态"
                                >
                                    <Radio.Group>
                                        <Radio value={-2}>已删除</Radio>
                                        <Radio value={-1}>不通过</Radio>
                                        <Radio value={0}>审核中</Radio>
                                        <Radio value={1}>通过</Radio>
                                    </Radio.Group>
                                </Form.Item>
                            </Col>
                        </Row>

                        <div style={{overflowWrap:"anywhere"}}>
                            壁纸路径：
                            <br></br>
                            {wallpaper.path}
                            <br></br>
                            其他信息:
                            <br></br>
                            总分数：{wallpaper.score}
                            <br></br>
                            互动分数：{wallpaper.interactScore}
                            <br></br>
                            喜欢：{wallpaper.likes}，收藏：{wallpaper.subscribes}，分享：{wallpaper.shares}
                            <br></br>
                            <span style={{color:"#FF2222"}}>不喜欢：</span>{wallpaper.dislikes}
                        </div>
                    </Form>
                </Drawer>
            </div>
        );
    }


}

export default WallpaperObject;